<script setup lang="ts">
import { inject, nextTick, onMounted, ref, type Ref } from 'vue'
import axios from 'axios'

import readsql from '../utils/ReadSql'
import ctrlsql from '../utils/ControlSql'

import BaseFrame from '../components/BaseFrame.vue'
import ManagerPanel from '../components/icons/ManagerPanel.vue'

const tencent_key = inject('$tencent-key')

const block_margin_left = ref('256')
const block_width = ref('1200')

interface BlockFormData {
  margin_left: string,
  width: string
}
const getBlockForm = (data: BlockFormData) => {
  block_margin_left.value = data.margin_left
  block_width.value = data.width
  console.log(data)
}

// for subdom baseframe
const page_title = '哈尔滨市停车场点位数据列表'

// for subdom managerpanel
const table_name = 'Park'
const table_labels = ['id', 'name', 'location', 'moment_capacity', 'park_representative']
const table_display_names = ['编号', '名称', '地址', '现容量', '停车场法人']
const table_data: Array<Object> = []
const table_data_format: Array<Array<string>> = [
  ['park_representative', 'obj_msg']
]
const ctrl_btn = ['delete', 'edit']
const ctrl_url = {
  base: '/api/sql-deal',
}
const editListLabels: Array<string> = []
const editListTypes: Array<string> = []
const editListOptions: Map<number, Object> = new Map()
const edit_options = {
  editListLabels,
  editListTypes,
  editListOptions,
}
const title = '地图'
const detail_labels = ['name', 'location', 'moment_capacity', 'park_representative']
const detail_display_names = ['名称', '地址', '现容量', '停车场法人']
const detail_label_options = new Map([
  ['park_representative', 'obj_msg']
])

// for init
const table_label_types = ['number', 'string', 'string', 'number', 'string']

const showDiv = ref(0)
const addModel = ref(false)
const addConfirmStyle = ref('primary')
const addConfirmText = ref('确定')

const parkName = ref('')
const parkLocateName = ref('')
const parkDetailLocation = ref('')
const parkLocateIndex = ref([-1, -1])
const parkMaxCapacity = ref(1000)
const parkApi = ref('')
const parkNote = ref('')
const parkRepresent = ref('')
const parkMaxiumnHeight = ref(5)
const addParkAdmin = ref(false)

const initParkList = () => {
  readsql.readSQL({
    table: table_name,
    keys: table_labels,
    key_types: table_label_types,
    where: null,
    where_key: null,
    group_by_keys: null,
    order_by_keys: null,
    limit: null,
  }).then((res) => {
    if (res['data']['ok']) {
      for (var idx = 0; idx < res['data']['data'].length; idx += 1) {
        table_data.push(res['data']['data'][idx])
      }
      nextTick(() => { showDiv.value += 1 })
    } else {
      alert('数据处理层错误，联系技术人员')
    }
  })
}

const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  if (queryString) {
    axios({
      url: '/tencent-map',
      method: 'get',
      params: {
        key: tencent_key,
        keyword: queryString,
        region: '哈尔滨',
        region_fix: 1,
      },
    }).then((res) => {
      const target = res.data.data
      const results = target.map((me: any) => {
        return {
          value: me.title,
          address: me.address,
          lat: me.location.lat,
          lng: me.location.lng,
        }
      })
      cb(results)
    }).catch(err => {
      console.error(err)
    })
  } else {
    cb([])
  }
}

const handleSelect = (item: any) => {
  // console.log(item.address)
  parkDetailLocation.value = item.address
  parkLocateIndex.value[0] = item.lat
  parkLocateIndex.value[1] = item.lng
}

const openAddModel = () => {
  addConfirmStyle.value = 'primary'
  addConfirmText.value = '确定'

  parkName.value = ''
  parkLocateName.value = ''
  parkDetailLocation.value = ''
  parkLocateIndex.value = [-1, -1]
  addParkAdmin.value = false
  addModel.value = true
}

const confirmAdd = () => {

  // 确认信息填充完整
  const msgConfirm = () => {
    return parkName.value && parkLocateName.value &&
      parkDetailLocation.value && parkLocateIndex.value[0] != -1 &&
      parkLocateIndex.value[1] != -1
  }

  // 确认添加
  if (msgConfirm()) {
    // 判断是否添加默认的地图管理员
    if (addParkAdmin.value) { /* block */ }

    // 执行添加指令
    ctrlsql.ctrlSQL({
      method: 'insert',
      table: 'Park',
      keys: [
        'name',
        'location',
        'location_detail',
        'maxiumn_capacity',
        'api',
        'note',
        'park_representative',
        'maxiumn_car_height'
      ],
      key_types: [
        'string',
        'string',
        'string',
        'number',
        'string',
        'string',
        'string',
        'number',
      ],
      values: [
        parkName.value,
        parkLocateName.value,
        parkDetailLocation.value,
        String(parkMaxCapacity.value),
        parkApi.value,
        parkNote.value,
        parkRepresent.value,
        String(parkMaxiumnHeight.value),
      ],
      where: [''],
      where_key: 'and',
      group_by_keys: null,
      order_by_keys: null,
      limit: null
    }).then((res) => {
      if (res['data']['ok']) {
        setTimeout(() => {
          addConfirmStyle.value = 'success'
          addConfirmText.value = '添加成功'
          location.reload()
        }, 3000)
      } else {
        addConfirmStyle.value = 'danger'
        addConfirmText.value = '数据处理层错误，联系技术人员'
      }
    }).catch(err => {
      console.error(err)
    })
  } else {
    addConfirmStyle.value = 'danger'
    addConfirmText.value = '完善必填项'
  }
  addModel.value = false
}

onMounted(() => {
  initParkList()
})
</script>

<template>
  <BaseFrame :page_title="page_title" @get-block-form_="getBlockForm" />
  <div class="block__" :style="{ marginLeft: block_margin_left + 'px', width: block_width, transition: '0.34s'}">
    <el-button @click="openAddModel()" style="margin-bottom: 5px;">添加停车场</el-button>
    <ManagerPanel :key="showDiv" :title="title" :table_data="table_data" :table_labels="table_labels"
      :table_name="table_name" :ctrl_url="ctrl_url" :table_display_names="table_display_names"
      :table_data_format="table_data_format" :ctrl_btn="ctrl_btn" :edit_options="edit_options"
      :detail_labels="detail_labels" :detail_label_options="detail_label_options"
      :detail_display_names="detail_display_names" />

    <el-dialog v-model="addModel" title="添加停车场" width="40%">
      <div class="input-area">
        <div class="input-group">
          <label><span class="required-label">*</span>停车场名称</label>
          <el-input placeholder="请输入停车场名称" v-model="parkName" />
        </div>
        <div class="input-group">
          <label><span class="required-label">*</span>停车场地段名称</label>
          <!-- auto complete -->
          <el-autocomplete v-model="parkLocateName" :fetch-suggestions="querySearchAsync" placeholder="请输入地段名称"
            @select="handleSelect" style="width: 100%;" :trigger-on-focus="false" />
        </div>
        <div class="input-group">
          <label><span class="required-label">*</span>停车场地段详细地址</label>
          <el-input placeholder="请输入停车场详细地段名称" v-model="parkDetailLocation" />
        </div>
        <div class="input-group">
          <label><span class="required-label">*</span>lat坐标</label>
          <el-input placeholder="停车场详细lat坐标" v-model="parkLocateIndex[0]" />
        </div>
        <div class="input-group">
          <label><span class="required-label">*</span>lng坐标</label>
          <el-input placeholder="停车场详细lng坐标" v-model="parkLocateIndex[1]" />
        </div>
        <div class="input-group">
          <label>停车场最大容量</label>
          <el-input placeholder="请输入停车场最大容量" v-model="parkMaxCapacity" />
        </div>
        <div class="input-group">
          <label>停车场负责人</label>
          <el-input placeholder="请输入停车场负责人名字" v-model="parkRepresent" />
        </div>
        <div class="input-group">
          <label>停车场车辆限高</label>
          <el-input placeholder="请输入停车场车辆限高" v-model="parkMaxiumnHeight" />
        </div>
        <div class="input-group">
          <label>停车场系统接口</label>
          <el-input placeholder="请输入停车场系统接口" v-model="parkApi" />
        </div>
        <div class="input-group">
          <label>停车场注意事项</label>
          <el-input placeholder="请输入停车场注意事项" v-model="parkNote" />
        </div>
        <div>
          <label style="margin-right: 10px; margin-top: 10px;">是否添加地图管理员</label>
          <el-switch v-model="addParkAdmin" />
        </div>
      </div>


      <template #footer>
        <span class="model-footer">
          <el-button @click="addModel = false">取消</el-button>
          <el-button @click="confirmAdd()" :type="addConfirmStyle" id="add-confirm">{{ addConfirmText }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.required-label {
  color: red;
}
</style>